<?php namespace App\Services\FontService;
/**
 * 字体API
 *
 * 字体service
 *
 * @author    zhouchao <zhouchao@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
use App\Services\BaseService;
use App\Services\Exceptions\EntityNotFoundException;
use App\Services\Exceptions\PriceErrorException;
use App\Services\PreferentialService\PreferentialService;
use App\Services\Tool\GeneralTool;
use DB;

class FontService extends BaseService{

    public function font_exit($font_id){
        $this->setParameter(array(
            'table' => 'fonts',
            'where' => array(
                array('font_id','=',$font_id),
                array('state','=',1)
            )
        ));
        $font_num = $this->count();
        return empty($font_num) ? false : true;
    }
    /**
     * 获取字体价格
     * @param $font_id
     * @return bool
     */
    public function getFontPrice($font_id){
        $this->table = 'fonts';
        $this->where = array(array('font_id','=',$font_id));
        $this->select = array('price');
        $font = $this->getById();
        return empty($font) ? false : GeneralTool::priceFormat($font->price);
    }

    /**
     * 根据字体ID获取字体
     * @param $font_id
     * @return mixed
     * @throws EntityNotFoundException
     * @throws PriceErrorException
     */
    public function get_font_by_id($font_id){
        $this->setParameter(array(
            'table' => 'fonts',
            'where' => array(
                array('font_id','=',$font_id),
                array('state','=',1)
            ),
            'select'=> array('font_id as source_pic_id','font_name as source_pic_name','font_image as thumbnail','price as original_price')
        ));
        $font = $this->getById();
        if(empty($font)){
            throw new EntityNotFoundException('未找到ID为'.$font_id.'的字体');
        }
        $font->thumbnail = env('IMG_URL_STD_PREFIX').$font->thumbnail;
        $font->original_price  = GeneralTool::priceFormat($font->original_price);
        $prices = PreferentialService::getResourcePrice($font_id, 3);
        if ($prices === false || $prices['original_price'] === false || $prices['preferential_price'] === false) {
            throw new PriceErrorException('ID为' . $font_id . '的字体价格异常');
        }
        $font->preferential_price = GeneralTool::priceFormat($prices['preferential_price']);
        $font->type = 3;
        $font->user_id = 0;
        return $font;
    }

    public function get_font_by_font_id($font_id){
        $this->setParameter([
            'table' => 'fonts',
            'where' => [['font_id','=',$font_id]],
            'select'=> ['font_type','font_path','font_name']
        ]);
        $font = $this->getById();
        if(!empty($font)){
            $font_path = explode('/',$font->font_path);
            $font->font_path = end($font_path);
        }
        return $font;
    }

    /**
     * 获得所有字体
     * @param $user_id
     * @param int $per_page
     * @return array
     */
    public function getList($user_id,$per_page = 10){
        $this->setParameter([
            'table' => 'fonts',
            'where' => [['state','=',1],['is_default','<>',1]],
            'select'=> ['font_id','font_name','font_image','font_path','font_type','is_stand_by_apecial_font'],
            'order' => 'font_downloads',
            'sort'  => 'desc'
        ]);
        $fonts = $this->getAllPaginated($per_page)->toArray();
        $font_array = array();
        foreach($fonts['data'] as $font){
            $font->font_path = env('FONT_URL_STD_PREFIX').$font->font_path;
            $font->font_image = $this->setImagePath($font->font_image);
            $this->setParameter([
                'table' => 'user_fonts',
                'where' => [['user_id','=',$user_id],['font_id','=',$font->font_id],['state','=',1]],
            ]);
            $font_num = $this->count();
            $font->download = $font_num == 0 ? 0 : 1;
            //获取字体价格
            $prices = PreferentialService::getResourcePrice($font->font_id, 3);
            $font->original_price = GeneralTool::priceFormat($prices['original_price']);
            $font->preferential_price = GeneralTool::priceFormat($prices['preferential_price']);
            $font_array[] = $font;
        }
        $result = array('total_page'=>$fonts['last_page'],'current_page'=>$fonts['current_page'],'per_page'=>$per_page,'data'=>$font_array);
        return $this->createResult('M00000',$result);
    }

    /**
     * 搜索字体
     * @param $user_id
     * @param $search
     * @param int $per_page
     * @return array
     */
    public function get_search_font($user_id,$search,$per_page = 10){
        $this->setParameter([
            'table' => 'fonts',
            'where' => [['font_name','like','%'.$search.'%'],['state','=',1]],
            'select'=> ['font_id','font_name','font_image','font_path','font_type'],
            'order' => 'font_downloads',
            'sort'  => 'desc'
        ]);
        $fonts = $this->getAllPaginated($per_page)->toArray();
        $font_array = array();
        foreach($fonts['data'] as $font){
            $font->font_path = env('FONT_URL_STD_PREFIX').$font->font_path;
            $font->font_image = $this->setImagePath($font->font_image);
            $this->setParameter([
                'table' => 'user_fonts',
                'where' => [['user_id','=',$user_id],['font_id','=',$font->font_id],['state','=',1]],
            ]);
            $font_num = $this->count();
            $font->download = $font_num == 0 ? 0 : 1;
            //获取字体价格
            $prices = PreferentialService::getResourcePrice($font->font_id, 3);
            $font->original_price = GeneralTool::priceFormat($prices['original_price']);
            $font->preferential_price = GeneralTool::priceFormat($prices['preferential_price']);
            $font_array[] = $font;
        }
        $result = array('total_page'=>$fonts['last_page'],'current_page'=>$fonts['current_page'],'per_page'=>$per_page,'data'=>$font_array);
        return $this->createResult('M00000',$result);
    }

    /**
     * 下载
     * @param $user_id
     * @param $font_id
     */
    public function download($user_id,$font_id){
        //判断是否存在
        $this->setParameter([
            'table' => 'user_fonts',
            'where' => [['user_id','=',$user_id],['font_id','=',$font_id]],
            'select'=> 'state'
        ]);
        $font = $this->getById();
        $result = 1;
        if(!empty($font)){
            if($font->state == 2){
                $this->setParameter([
                    'table' => 'user_fonts',
                    'where' => [['user_id','=',$user_id],['font_id','=',$font_id]]
                ]);
                $data = ['state'=>1,'updated_at'=>time()];
                $result = $this->update($data);
            }
        }else{
            $this->setParameter([
                'table' => 'user_fonts'
            ]);
            $data = ['user_id'=>$user_id,'font_id'=>$font_id,'created_at'=>time(),'updated_at'=>time()];
            $result = $this->save($data);
        }
        if(empty($result)){
            return $this->createResult('M00003',(object)array());
        }
        //增加下载量
        DB::table('fonts')->where('font_id',$font_id)->increment('font_downloads');
        return $this->createResult('M00000',(object)array());
    }

    /**
     * 获得已下载
     * @param $user_id
     * @param int $per_page
     * @return array
     */
    public function getdownloadFonts($user_id,$per_page = 10){
        $this->setParameter([
            'table' => 'user_fonts',
            'where' => [['user_id','=',$user_id],['state','=',1]],
            'select'=> ['font_id'],
            'order' => 'updated_at',
            'sort'  => 'desc'
        ]);
        $fonts = $this->getProductListByModuleId($this,$per_page);
        return $this->createResult('M00000',$fonts);
    }

    /**
     * 卸载
     * @param $user_id
     * @param $font_id
     * @return mixed
     */
    public function unistall($user_id,$font_id){
        $this->setParameter([
            'table' => 'user_fonts',
            'where' => [['user_id','=',$user_id],['font_id','=',$font_id]]
        ]);
        $data = array('state'=>2,'updated_at'=>time());
        $result = $this->update($data);
        return $this->createResult('M00000',(object)array());
    }

    public function getListByReSourceIds($resource_ids){
        $this->table = 'fonts';
        $this->select = [
            'font_id','font_name','font_image','font_path','font_type','state'
        ];
        $fonts = array();
        foreach($resource_ids as $resource_id){
            $this->where = [['font_id','=',$resource_id->font_id]];
            $font = $this->getById();
            if(!empty($font)){
                $font->font_path = env('FONT_URL_STD_PREFIX').$font->font_path;
                $font->font_image = $this->setImagePath($font->font_image);
                $font->download = 1;
                //获取字体价格
                $prices = PreferentialService::getResourcePrice($font->font_id, 3);
                $font->original_price = GeneralTool::priceFormat($prices['original_price']);
                $font->preferential_price = GeneralTool::priceFormat($prices['preferential_price']);
                $fonts[] = $font;
            }
        }
        return $fonts;
    }

    /**
     *
     * @param $product_temp_id
     * @param $colour_id
     * @param $price
     * @return bool
     */
    public static function updateFontPrice($font_id,$price){
        $price=floatval($price);
        $font_id=intval($font_id);
        $update_res=DB::table('fonts')->where(array(
            'font_id'=>$font_id,
            'state'=>1
        ))->update(array(
            'price'=>$price,
            'updated_at'=>time(),
        ));
        return ($update_res>0)?true:false;
    }
}